<template>
    <div class="album-page">
      <div class="header">
        <div class="container">
          <Header />
        </div>
      </div>
      <div class="main">
        <div class="container">
          <h2 class="album-title">相册</h2>
          <div class="waterfall" v-if="photos.length" ref="waterfallContainer">
            <div
              v-for="photo in photos"
              :key="photo.id"
              class="waterfall-item"
              :style="{ width: `${columnWidth}px` }"
            >
              <div class="photo-card">
                <el-image
                  :src="absoluteUrl(photo.url)"
                  fit="cover"
                  lazy
                  @click="openViewer(photo.id)"
                  class="photo-image"
                />
                <div class="photo-info">
                  <p class="photo-title">{{ photo.title }}</p>
                  <el-button
                    type="primary"
                    size="small"
                    @click="downloadPhoto(photo.url)"
                    class="download-button"
                  >
                    下载
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          <el-empty v-else description="暂无图片" />
          <el-image-viewer
            v-if="showViewer"
            :url-list="photoUrls"
            :initial-index="currentIndex"
            @close="showViewer = false"
          />
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue';
  import { ElMessage } from 'element-plus';
  import Header from '@/components/layout/Header.vue';
  import frontApi from '@/api/front';
  
  const photos = ref([]);
  const showViewer = ref(false);
  const currentIndex = ref(0);
  const waterfallContainer = ref(null);
  const columnCount = ref(4); // 默认 4 列
  const columnWidth = ref(0);
  
  const photoUrls = computed(() => photos.value.map((p) => absoluteUrl(p.url)));
  
  const absoluteUrl = (url) => {
    return url.startsWith('http') ? url : `${import.meta.env.VITE_API_BASE_URL}${url}`;
  };
  
  const fetchPhotos = async () => {
    try {
      const res = await frontApi.getPhotos();
      photos.value = res.data;
      await nextTick();
      arrangeWaterfall();
    } catch (err) {
      ElMessage.error('获取图片失败');
      console.error('获取图片失败:', err);
    }
  };
  
  const openViewer = (id) => {
    currentIndex.value = photos.value.findIndex((p) => p.id === id);
    showViewer.value = true;
  };
  
  const downloadPhoto = (url) => {
    const absolute = absoluteUrl(url);
    const link = document.createElement('a');
    link.href = absolute;
    link.download = absolute.split('/').pop();
    link.click();
  };
  
  const arrangeWaterfall = () => {
    if (!waterfallContainer.value) return;
  
    const containerWidth = waterfallContainer.value.offsetWidth;
    const gap = 16;
    columnWidth.value = (containerWidth - gap * (columnCount.value - 1)) / columnCount.value;
  
    const items = Array.from(waterfallContainer.value.children);
    const columnHeights = Array(columnCount.value).fill(0);
  
    items.forEach((item) => {
      const minHeight = Math.min(...columnHeights);
      const columnIndex = columnHeights.indexOf(minHeight);
      item.style.position = 'absolute';
      item.style.top = `${minHeight}px`;
      item.style.left = `${columnIndex * (columnWidth.value + gap)}px`;
      columnHeights[columnIndex] += item.offsetHeight + gap;
    });
  
    waterfallContainer.value.style.height = `${Math.max(...columnHeights)}px`;
  };
  
  const updateColumnCount = () => {
    const width = window.innerWidth;
    if (width < 768) {
      columnCount.value = 2;
    } else if (width < 1024) {
      columnCount.value = 3;
    } else {
      columnCount.value = 4;
    }
    nextTick(() => arrangeWaterfall());
  };
  
  onMounted(() => {
    fetchPhotos();
    updateColumnCount();
    window.addEventListener('resize', updateColumnCount);
  });
  
  onUnmounted(() => {
    window.removeEventListener('resize', updateColumnCount);
  });
  </script>
  
  <style scoped lang="scss">
  .container {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 16px;
  }

  .header {
    background: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    position: sticky;
    top: 0;
    z-index: 100;
    .container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 64px;
    }
  }

  .main {
    padding: 48px 0 40px 0;
    background: #fafbfc;
  }

  .album-title {
    font-size: 28px;
    font-weight: 700;
    color: #222;
    margin-bottom: 24px;
    text-align: center;
  }

  .waterfall {
    position: relative;
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
  }
  
  .waterfall-item {
    transition: all 0.3s ease;
  }
  
  .photo-card {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    overflow: hidden;
    margin-bottom: 24px;
    display: flex;
    flex-direction: column;
  }
  
  .photo-image {
    width: 100%;
    height: 240px;
    object-fit: cover;
    background: #f4f6fb;
    cursor: pointer;
  }
  
  .photo-info {
    padding: 20px;
    color: #555;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .photo-title {
    font-size: 18px;
    font-weight: 600;
    color: #222;
    margin-bottom: 8px;
  }
  
  .photo-desc {
    color: #888;
    font-size: 15px;
    margin-bottom: 8px;
  }
  
  .download-button {
    background: #2563eb;
    border-color: #2563eb;
    border-radius: 6px;
    &:hover {
      background: #1d4ed8;
      border-color: #1d4ed8;
      transform: scale(1.02);
    }
  }

  @media (max-width: 768px) {
    .main {
      padding: 18px 0;
      background: #fafbfc;
    }
    .photo-card {
      border-radius: 12px;
    }
    .photo-image {
      height: 160px;
    }
  }
  </style>